<?php
namespace Home\Model;
use Think\Model;

class UserModel extends BaseModel {

	protected $tableName = 'tp_user';

	/**
	 * @desc: 校验手机号唯一性
	 * @Author: delayhsiao
	 * @update: 2016-11-22
	 **/
	public function checkMobileRepeat($mobile){
		$repeat = $this->where(array('f_user_mobile'=>$mobile))->count();
		if($repeat > 0){
			return false;
		}else{
			return true;
		}
	}
	
	/**
	 * @desc: 用户登录信息验证
	 * @Author: quyang
	 * @update: 2016-11-22
	 **/
	public function userInformation($where){
	    $list = $this->where($where)->find();
	    return $list;
	}
	
	/**
	 * @desc: 用户登录信息查询
	 * @Author: quyang
	 * @update: 2016-11-22
	 **/
	public function userlogin($where){
	    $arr = $this->alias('u')
	    ->where($where)
	    ->field('
                u.f_user_id as fUserId,
                u.f_area_name as areaName,
                u.f_city_name as cityName,
                u.f_province_name as privinceName,
                u.f_user_email as fUserEmail,
                u.f_address as address,
                u.f_area_id as areaId,
                u.f_city_id as cityId,
                u.f_user_mobile as fUserMobile,
                u.f_user_name as fUserName,
                u.f_user_phone as fUserPhone,
                u.f_user_pwd as fUserPwd,
                u.f_user_status as fUserStatus,
                u.f_user_type_id as fUserTypeId,
                u.f_province_id as privinceId,
                u.f_main_business as companyName,
                u.f_station_name as stationName,
                u.f_store_time as storeTime,
                u.f_company_id as companyId,
                u.f_company_name as companyName,
                u.f_expire_time as fExpireTime,
                u.f_bond as fBond,
                u.f_addition_status as state,
                u.`f_professional` as `fProfessional`,
                u.f_speed_status as fSpeedStatus,
                u.f_jurisdiction_type as fJurisdictionType,
                e.f_company_initials as companyNamePY,
                0 as fStationType,
                u.f_packetnum_repeat as packetnumRepeat,
                u.f_api_type as apiType
                ')
            ->join('left join tp_express_company e ON u.f_company_id = e.f_company_id')
            ->find();

	    //fJurisdictionType  字段为登录权限  用户权限  0.通用  1.享买系统  2.包裹系统
        //companyNamePY   为快递员快递公司简拼  2017-4-24  quyang

	    if ($arr == false){
	        return false;
        }

        if ( !preg_match('/^\d{14}$/', $arr['fExpireTime']) ){
	        $arr['fEndStatus'] = '0';
        }else{
            //账户到期时间<当前时间则该账户已过期需重新支付套餐  0：正常使用 1：已过期
//            $arr['fEndStatus'] = $arr['fExpireTime'] < date('YmdHis') ? '1' : '0';
            $arr['fEndStatus'] = '0';
        }

        //如果没有提交审核资料则没有该bean，返回null
        $list = $this
            ->where(array('f_user_id'=>$arr['fUserId']))
            ->field('
                f_user_id as fUserId,
                f_user_id as userId,
                f_user_id as UserId,
                f_addition_create_time as fCreateTime,
                f_user_crad_no as identityNo,
                f_main_business as mainBusiness,
                f_addition_status as state,
                f_user_real_name as userRealName,
                f_addition_time as verifyTime,
                f_addition_type as verifyType,
                f_addition_user_id as verifyUser,
                0 as verifyId
               ')->find();
        $arr['verifyBean'] = $list;
        $arr['verifyBean']['address']=$arr['address'];
        $arr['verifyBean']['areaId']=$arr['areaId'];
        $arr['verifyBean']['cityId']=$arr['cityId'];
        $arr['verifyBean']['privinceId']=$arr['privinceId'];


        $arr['verifyBean']['state'] = empty( $arr['verifyBean']['cityId'] ) ? '' : $arr['verifyBean']['state'];

	    return $arr;
	}

    /**
     * 查询用户信息用于替换模板
     * @param type $uid 用户id
     * @author cheng
     */
    public function getUserInfo($uid) {
        $result = $this->alias('u')
                ->field('   u.f_province_id,
                            u.f_city_id,
                            u.f_area_id,
                            u.f_address,
                            u.f_station_name,
                            u.f_store_time,
                            u.f_user_id,
                            u.f_user_name, 
                            u.f_user_pwd,
                            u.f_user_mobile,
                            u.f_user_phone,
                            u.f_user_email,
                            u.f_user_status,
                            u.f_bond,
                            u.f_user_type_id,
                            u.f_expire_time,
                            u.f_create_time,
                            u.f_proxy_id,
                            u.f_contract_url,
                            u.f_province_name,
                            u.f_city_name,
                            u.f_user_crad_no,
                            u.f_area_name')
                ->where(array('u.f_user_id' => $uid))
                ->find();
        //删除f_station_type   1-19
//        u.f_station_type,
        return $result;
    }

    /**
     * @deac 查询短信余量
     * @front 短信发送方法
     * @author quyang
     * @again quyang 2017-1-18
     * @update 2016-11-29
     */
    public function getSms($station,$code){
        $where = array('f_user_id'=>$station);
        $data = $this->where($where)->find();
        if ($data == false){
            return false;
        }
        //短信条数小于0包裹状态改为待完善
        if ($data['f_buy_count'] <= '0'){
            D('Home/ParcelInfo')->updateStatus($code,2);
            return false;
        }
        return $data;
    }

    /**
     * @desc 修改短信余额
     * @author quyang
     * @again quyang 2017-1-18
     * @update 2016-12-1
     */
    public function updateSms($station,$smsnum){
        $this->where(array('f_user_id'=>$station))->setDec('f_buy_count',$smsnum);
    }

    /**
     * 查询附近站点列表数据
     * @again quyang 2017-01-18
     * @author cheng
     */
    public function getNearbyStation($map, $page, $nums ,$status, $expId = 0) {
        $count = $this->alias('u')
            ->field('count(DISTINCT(u.f_user_id)) as totals')
            ->where($map)
            ->find();
        $list = $this->alias('u')
            ->field("u.f_user_id as stationId,
            u.f_station_name as stationName,
            u.f_store_time storeTime,
            u.f_user_id as userId,
            u.f_url as url,
            u.f_address as address,
            u.f_user_mobile as mobile,
            u.f_main_business as fMainBusiness,
            'http://7xtbpc.com1.z0.glb.clouddn.com/xmkslogo_12.png' as `fFace`,
            '$status' as `fStatus`,
            u.f_user_phone as phone"
            )
//            ,
//            `tp_express_branch_com_dz`.`continual_use`

//            ->join("`tp_express_branch_com_dz` ON `tp_express_branch_com_dz`.`f_station_id` = `u`.`f_user_id` AND `tp_express_branch_com_dz`.`f_exp_id` = '{$expId}'", "left")
            ->where($map)
            ->group('u.f_user_id')
            ->page($page, $nums)
            ->select();
        foreach ($list as $k => $v) {
            $list[$k]['url'] = $v['url'] ? $v['url'] : C('IMG_URL').'static/defaultStation.jpg';
        }
        $data['totalPage'] = ceil($count['totals'] / $nums);
        $data['totalCount'] = $count['totals'];
        $data['stationList'] = $list;
        return $data;
    }

    /**
     * @desc 短信统计模型
     * @author quyang
     * @again quyang 2017-1-18
     * @update 2016-11-24
     */
    public function countsms($where,$id){
        $data = $this
            ->where($where)
            ->field('f_buy_count AS buyAviliable,f_expire_time as fExpireTime')->find();
        if($data == false){
            return false;
        }

        //判断到期时间
        if ( !preg_match('/^\d{14}$/', $data['fExpireTime']) ){
            $data['fEndStatus'] = '0';
        }else{
            //账户到期时间<当前时间则该账户已过期需重新支付套餐  0：正常使用 1：已过期
//            $data['fEndStatus'] = $data['fExpireTime'] < date('YmdHis') ? '1' : '0';
            $data['fEndStatus'] = '0';
        }

        //NULL 转 0
//        $data['buyAviliable'] = intval( $data['buyAviliable'] );

        $data['smsPackagetotal'] = '0';
        $data['curCount'] = '0';
        //根据userId获取所有充值数量总和
        $arr = D('Home/RechargeMsgLog')->field('SUM(f_msg_num) as num')->where(array('f_user_id'=>$id))->select();
        $data['buyTotal'] = $arr[0]['num'];
        if ($data['buyTotal'] == null){
            $data['buyTotal']='0';
        }
        $smstotal = $data['buyTotal']+$data['smsPackagetotal'];
        $packageaviliable = $data['curCount']+$data['buyAviliable'];
        $data['smsPackageAviliable'] = "$packageaviliable";
        $allAviliable = $data['smsPackageAviliable']+$data['buyAviliable'];
        $data['allAviliable'] = "$allAviliable";
        $data['smstotal'] = "$smstotal";
        $data['allAviliable'] = $data['buyAviliable'];
        return $data;
    }


    /**
     * @desc: 根据用户id修改审核状态为通过
     * @param type $uid 用户id
     * @Author: cheng
     **/
    public function saveStatus($uid,$endTime){

        //添加账户有效期结束时间  201-2-17
        $result = $this->where(['f_user_id'=>$uid])->save(['f_addition_status' => 1, 'f_addition_time' => date('YmdHis'),'f_expire_time'=>$endTime]); //审核通过
        return $result;
    }

    /**
     * Function updateStationInfo
     * @param $data
     *
     * Author: quyang
     * Date: 2017-2-4 11:40
     * Info: 修改站点营业时间
     */
    public function updateStationInfo($data){

        $where['f_store_time'] = $data['storeTime'];

        $where['f_user_id'] = $data['stationId'];

        $list = $this->save($where);

        if ($list === false){
            return false;
        }

        return true;

    }


    /**
     * Function updataPhone
     * @param $method
     * @return mixed
     *
     * Author: quyang
     * Date: 2017-2-5 11:08
     * Info: 修改联系方式
     */
    public function updatePhone($method){

        $where['f_user_id'] = $method['stationId'];

        $where['f_user_phone'] = $method['phone'];

        $data = $this->save($where);

        return $data;

    }

    /**
     * Function updataPassword
     * @param $method
     * @return mixed
     *
     * Author: quyang
     * Date: 2017-2-5 11:08
     * Info: 修改密码
     */
    public function updatePassword($method){

        //修改类型为1修改密码时验证userid    0是找回密码不验证userid
        if ( $method['operationType'] == 1 )
        {
            $where['f_user_id'] = $method['userId'];
        }

        $where['f_user_mobile'] = $method['mobile'];

        $map['f_user_pwd'] = $method['password'];

        $data = $this->where($where)->save($map);

        return $data;

    }

    /**
     * Function stationInfo
     * @param $method
     *
     * Author: quyang
     * Date: 2017-2-8 21:48
     * Info: 获取站点营业时间
     */
    public function stationInfo($method){

        return $this->where($method)->field('
                         0 as app,
                         0 as weixin,
                         0 as sms,
                         f_station_name as stationName,
                         f_store_time as storeTime,
                         f_user_id as stationId
        ')->find();

    }

    /**
     * @desc 根据区域选择代理
     * @author quyang
     * @update 2017-02-18
     */
    public function queryProxyInfo($where){

        return $this->where($where)->getField('f_user_id',true);

    }
    
    /**
     * @desc 根据f_station_id获取省市区信息
     * @author cheng
     * @update 2017-06-09
     */
    public function getArea($f_station_id) {
        $map['f_user_id'] = $f_station_id;
        return $this->field('f_province_id,f_province_name,f_city_id,f_city_name,f_area_id,f_area_name')->where($map)->find();
    }
    
    /**
     * 获取站点信息列表
     * @desc sql按照java上写的
     * @author cheng
     */
    public function getStationList($map, $page, $size) {
        $data['count'] = $this->alias('u')->field('si.f_user_id')
                ->join('left join tp_user up ON u.f_user_id = up.f_user_id')  //代理名称
                ->where($map)
                ->count();
        $data['list'] = $this->alias('u')
                ->field('
                    u.f_user_id,
                    u.f_station_name,
                    u.f_store_time,
                    u.f_user_mobile,
                    u.f_user_name,
                    u.f_user_status,
                    u.f_address,
                    u.f_province_name,
                    u.f_province_id,
                    u.f_city_id,
                    u.f_area_id,
                    u.f_city_name,
                    u.f_area_name,
                    u.f_buy_count,
                    u.f_proxy_id,
                    up.f_user_name as fProxyName
                    ')
                ->join('left join tp_user up ON u.f_proxy_id = up.f_user_id')  //代理名称
                ->where($map)
                ->order('u.f_user_id desc')
                ->page($page, $size)
                ->select();
        return $data;
    }
}